require('es6-promise').polyfill();

import axios from 'axios'


export function apiMsgAction(msg) {
  return {
    type: 'API_MSG',
    msg
  }
}

function loadNewsHandler(data) {
  return {
    type: 'LOAD_NEWS_DATA',
    data
  }
}

function loadNewsThisMonthHandler(data) {
  return {
    type: 'LOAD_NEWS_THIS_MONTH_DATA',
    data
  }
}



export function loadNewsHandlerAsync(data) {
  return function(dispatch) {
    return axios.post('/api/news/', data).then(
      resp => dispatch(loadNewsHandler(resp.data)),
      error => dispatch(apiMsgAction(error.data.errMsg))
    );
  };
}

export function loadThisMonthHandlerAsync(data) {
  return function(dispatch) {
    return axios.post('/api/news/queryThisMonth', data).then(
      resp => dispatch(loadNewsThisMonthHandler(resp.data)),
      error => dispatch(apiMsgAction(error.data.errMsg))
    );
  };
}

export function createCombineNewsHandlerAsync(data) {
  return function(dispatch) {
    return axios.post('/api/news/combineNews', data)
    .then(function(resp) {
      dispatch(loadNewsHandlerAsync(data))
      dispatch(loadThisMonthHandlerAsync(data))
    })
    .catch(function (error) {
      dispatch(apiMsgAction(error.data.errMsg))
    })
  }
}

export function createSingleNewsHandlerAsync(data) {
  return function(dispatch) {
    return axios.post('/api/news/singleNews', data)
    .then(function(resp) {
      dispatch(loadNewsHandlerAsync(data))
      dispatch(loadThisMonthHandlerAsync(data))
    })
    .catch(function (error) {
      dispatch(apiMsgAction(error.data.errMsg))
    })
  }
}
